package com.chuanqi.common.utils;

import java.io.ByteArrayOutputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.OutputStreamWriter; 
import java.io.PrintWriter; 
import javax.servlet.RequestDispatcher; 
import javax.servlet.ServletContext; 
import javax.servlet.ServletException; 
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import javax.servlet.http.HttpServletResponseWrapper; 

public class HtmlGenerator {
	public static void createStaticHTMLPage(HttpServletRequest request, HttpServletResponse response,ServletContext servletContext,String fileName,String fileFullPath,String jspPath) throws ServletException, IOException{ 
    	response.setContentType("text/html;charset=UTF-8"); 
        RequestDispatcher dispatcher = servletContext.getRequestDispatcher(jspPath); 
        if(dispatcher != null){
        	System.out.println("notnull");
        }else{
        	System.out.println("null");
        }
        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 
        final ServletOutputStream servletOuputStream = new ServletOutputStream(){ 
            public void write(byte[] b, int off,int len){ 
                byteArrayOutputStream.write(b, off, len); 
            } 
            public void write(int b){ 
                byteArrayOutputStream.write(b); 
            }
			@Override
			public boolean isReady() {				
				return false;
			}
			@Override
			public void setWriteListener(WriteListener arg0) {				
				
			} 
        }; 
        final PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(byteArrayOutputStream)); 
        HttpServletResponse httpServletResponse = new HttpServletResponseWrapper(response){ 
            public ServletOutputStream getOutputStream(){ 
                return servletOuputStream; 
            } 
            public PrintWriter getWriter(){ 
                return printWriter; 
            } 
        }; 
        dispatcher.include(request, httpServletResponse); 
        printWriter.flush(); 
        FileOutputStream fileOutputStream = new FileOutputStream(fileFullPath); 
        byteArrayOutputStream.writeTo(fileOutputStream); 
        fileOutputStream.close(); 
        response.sendRedirect("chuanqi/"+fileName); 
    } 
}
